package com.todo.gateway.conf;

import com.todo.gateway.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

/**
 * @author azhebuxing
 * @date 2025/2/21 21:33
 * @description
 */
@Slf4j
@Component
public class JwtAuthenticationFilter implements WebFilter{

    @Resource
    private JwtUtils jwtUtils;

    //后续一些不需要做校验的接口也可以放在此处，例如首页一些数据等
    public static List<String> excludedPaths = Arrays.asList("/web/auth", "/m/auth", "/app/auth");


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {

        // 过滤不需要校验的接口前缀
        String path = exchange.getRequest().getPath().value();
        String requestId = exchange.getRequest().getId();
        log.info("JwtAuthenticationFilter called for path: {}, requestId: {}", path, requestId);
        for (String excludedPath : excludedPaths) {
            if (path.startsWith(excludedPath)) {
                return chain.filter(exchange);
            }
        }

        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            if (jwtUtils.validateToken(token)) {
                // 解析用户信息并注入请求头
                String username = jwtUtils.getUsernameFromToken(token);
                ServerHttpRequest modifiedRequest = request.mutate()
                        .header("X-User-Id", username)
                        .build();
                return chain.filter(exchange.mutate().request(modifiedRequest).build());
            }
        }

        // Token 无效，返回 401
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }


}
